package top.codef.config;

import java.util.HashMap;
import java.util.Map;

import javax.money.MonetaryAmount;

import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.RoundedMoney;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;

import top.codef.serializers.AbstractMoneyDeserializer;
import top.codef.serializers.AbstractMoneySerializer;

@Configuration
public class Jackson2MoneyMapperBuilderCustomizerConfig implements Jackson2ObjectMapperBuilderCustomizer {

	@Autowired
	private AbstractMoneySerializer<? extends MonetaryAmount> serializer;

	@Autowired
	private AbstractMoneyDeserializer<? extends MonetaryAmount> deserializer;

	@Override
	public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
		Map<Class<?>, JsonSerializer<?>> map = new HashMap<Class<?>, JsonSerializer<?>>();
		map.put(MonetaryAmount.class, serializer);
		map.put(FastMoney.class, serializer);
		map.put(RoundedMoney.class, serializer);
		map.put(Money.class, serializer);
		jacksonObjectMapperBuilder.serializersByType(map);
		Map<Class<?>, JsonDeserializer<?>> deMap = new HashMap<Class<?>, JsonDeserializer<?>>();
		deMap.put(MonetaryAmount.class, deserializer);
		deMap.put(FastMoney.class, deserializer);
		deMap.put(RoundedMoney.class, deserializer);
		deMap.put(Money.class, deserializer);
		jacksonObjectMapperBuilder.deserializersByType(deMap);
	}
}
